package com.mwy.springtimedemo.schedule;

import com.mwy.springtimedemo.job.MyJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class MyJobSchedu {

    public  static ConcurrentHashMap<String,Object> maileCache = new ConcurrentHashMap<String,Object>();
    public final static String mmailJobkey  = "mmailJobkey";
    public final static String mmailcron  = "mmailcron";
    public final static String checkTime  = "checkTime";

    @Autowired
    private Scheduler scheduler;

    @PostConstruct
    public void run() {
        Thread t = new Thread(new Runnable() {
            public void run() {
                try {
                    //创建调度器Scheduler
                    //创建JobDetail实例，并与Job类绑定(Job执行内容)
                    JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                            .withIdentity(mmailJobkey,"mmailJobkeyGroup").build();
                    //基于表达式构建触发器
//					String crons = info.getCron();
//					if(StringUtils.isEmpty(crons)) {
//						String crons = "* */6 * * *";
                    String crons = "*/2 * * * * ?";
//					}
                    CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(crons);
                    //用于构建触发器实例
                    CronTrigger cronTrigger = (CronTrigger) TriggerBuilder.newTrigger()
                            .withIdentity(mmailJobkey,"mmailJobkeyTrigger").withSchedule(cronScheduleBuilder).build();
                    //执行
                    scheduler.scheduleJob(jobDetail, cronTrigger);
                    scheduler.start();
                    maileCache.put(mmailJobkey, jobDetail.getKey());
                    maileCache.put(mmailcron, crons);
                } catch (SchedulerException e) {
                    System.out.println("出错了");
                }
            }
        });
        t.start();
    }
}
